package com.suse.common.util.mq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 消息生产者
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-10-25 17:30
 */
public class MessageBroker<T> {

    private final BlockingQueue<T> blockingQueue = new ArrayBlockingQueue<>(1024*1024);

    private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,4,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(200));

    private MessageConsumer<T> consumer;

    public MessageBroker(MessageConsumer<T> consumer) {
        this.consumer = consumer;
        listen();
    }

    public void put(T message) {
        try {
            blockingQueue.put(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void listen() {
        threadPoolExecutor.execute(() -> {
            try {
                while(true) {
                    // 没有消息就一直阻塞
                    T message = blockingQueue.take();
                    consumer.consume(message);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        });
    }

}
